package com.holyn.guofang.presenter.login;

import android.Manifest;
import android.app.Activity;
import android.net.Uri;
import android.support.annotation.NonNull;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.MyApplication;
import com.holyn.guofang.bean.BaseResponseBean;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.RetrofitManager;
import com.holyn.guofang.model.webhttp.observable.UploadObservable;
import com.holyn.guofang.model.webhttp.observable.UserUnLoginObservable;
import com.holyn.guofang.model.webhttp.upload.ProgressRequestBody;
import com.holyn.guofang.model.webhttp.wo.UpdateInfoWo;
import com.holyn.guofang.model.webhttp.wo.UserInfoWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.utils.AppUniqueInfoUtil;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.mylibrary.utils.AppUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

/**
 * Created by Holyn on 2017/5/2.
 */

public class LoginPresenter extends LoginContract.Presenter{
    private final UserUnLoginObservable userUnLoginObservable;
    private final UploadObservable uploadObservable;
    private final RxDownload rxDownload;

    private LoginContract.View loginView;
    private LoginContract.UserInfoWoView loginCheckView;

    public LoginPresenter(@NonNull BaseView baseView) {
        super(baseView);

        userUnLoginObservable = RetrofitManager.getCommonObservable(UserUnLoginObservable.class);
        uploadObservable = RetrofitManager.getCommonObservable(UploadObservable.class);
        rxDownload = RxDownload.getInstance(MyApplication.getContext());
    }

    @Override
    public void addViewListener(LoginContract.View view) {
        this.loginView = view;
    }

    @Override
    public void addUserInfoWoViewListener(LoginContract.UserInfoWoView view) {
        this.loginCheckView = view;
    }

    @Override
    public void postLogin(String userName, String password, final int requestAction) {
        getCommonObservable(requestAction, userUnLoginObservable.login(userName, MD5Uitl.getMd5Value(password)))
                .subscribe(new Consumer<UserInfoWo>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull UserInfoWo userInfoWo) throws Exception {
                        loginView.responseSuccess(requestAction, userInfoWo);
                    }
                });

    }

    @Override
    public void postLoginB(String userName, String validCode, int requestAction) {
        getCommonObservable(requestAction, userUnLoginObservable.loginb(userName, validCode))
                .subscribe(new Consumer<UserInfoWo>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull UserInfoWo userInfoWo) throws Exception {
                        loginView.responseSuccess(requestAction, userInfoWo);
                    }
                });

    }

    @Override
    public void postLoginCheck(String userName, String validCode, int requestAction) {
        getCommonObservable(requestAction, userUnLoginObservable.loginCheck(userName, validCode))
                .subscribe(new Consumer<UserInfoWo>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull UserInfoWo userInfoWo) throws Exception {
                        loginCheckView.responseSuccess(requestAction, userInfoWo);
                    }
                });
    }

    @Override
    public void postPlatformUpdate(final int requestAction){
        Integer platformID = HttpConfigure.PLATFORM_TYPE_ANDROID;
        Integer version = AppUtil.getVersionCode(MyApplication.getContext());
        getCommonObservable(requestAction, userUnLoginObservable.platformUpdate(platformID, version))
                .subscribe(new Consumer<UpdateInfoWo>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull UpdateInfoWo updateInfoWo) throws Exception {
                        loginView.responseSuccessGetUpdateInfoWo(requestAction, updateInfoWo);
                    }
                });
    }

    @Override
    public void downloadNewApp(Activity activity, UpdateInfoWo updateInfoWo, int requestAction) {
        requestStart(requestAction);

        Disposable disposable = rxDownload.download(updateInfoWo.getUpdateInfo().getURL())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(downloadStatus -> {
                    //DownloadStatus为下载进度
                    LogUtils.d(downloadStatus);
                    loginView.responseDownloadNewAppStatus(requestAction, downloadStatus);
                }, throwable -> {
                    //下载失败
                    LogUtils.d("下载失败：" + throwable);
                    requestError(requestAction, throwable);
                }, () -> {
                    //下载成功
                    LogUtils.d("下载成功....");
                    File[] files = rxDownload.getRealFiles(updateInfoWo.getUpdateInfo().getURL());
                    if (files != null) {
                        Uri uri = Uri.fromFile(files[0]);
                        loginView.responseDownloadNewAppComplete(requestAction, uri);
                    }
                    requestComplete(requestAction);
                });






//        Disposable no_permission = new RxPermissions(activity)
//                .request(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
//                .subscribe(aBoolean -> {
//                    if (!aBoolean) {
//                        throw new RuntimeException("no permission");
//                    } else {
//
//                    }
//                });
//                .observeOn(Schedulers.io())
//                .compose(rxDownload.transform(updateInfoWo.getUpdateInfo().getURL()))
////                .compose(rxDownload.<Permission>transform(HttpConfigure.URL_WEI_XIN))//test
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<DownloadStatus>() {
//                    @Override
//                    public void accept(@io.reactivex.annotations.NonNull DownloadStatus downloadStatus) throws Exception {
//                        //DownloadStatus为下载进度
//                        LogUtils.d(downloadStatus);
//                        loginView.responseDownloadNewAppStatus(requestAction, downloadStatus);
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
//                        //下载失败
//                        LogUtils.d("下载失败：" + throwable);
//                        requestError(requestAction, throwable);
//                    }
//                }, new Action() {
//                    @Override
//                    public void run() throws Exception {
//                        //下载成功
//                        LogUtils.d("下载成功....");
//                        File[] files = rxDownload.getRealFiles(updateInfoWo.getUpdateInfo().getURL());
//                        if (files != null) {
//                            Uri uri = Uri.fromFile(files[0]);
//                            loginView.responseDownloadNewAppComplete(requestAction, uri);
//                        }
//                        requestComplete(requestAction);
//                    }
//                });

    }



    @Override
    public void postUploadTest(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"),file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file",file.getName(),
                    new ProgressRequestBody(requestBody, new ProgressRequestBody.Listener() {
                @Override
                public void onRequestProgress(long bytesWritten, long contentLength, long networkSpeed) {
                    LogUtils.d(file.getName()+" bytesWritten: "+bytesWritten);
                    LogUtils.d(file.getName()+" contentLength: "+contentLength);
                    LogUtils.d(file.getName()+" networkSpeed: "+networkSpeed);
                }
            }));
            parts.add(part);
        }

        uploadObservable.uploadFilesWithParts(parts)
            .subscribeOn(Schedulers.io())
                .flatMap(new Function<BaseResponseBean<String>, ObservableSource<BaseResponseBean<String>>>() {
                    @Override
                    public ObservableSource<BaseResponseBean<String>> apply(@io.reactivex.annotations.NonNull BaseResponseBean<String> stringBaseResponseBean) throws Exception {
                        return null;
                    }
                })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<BaseResponseBean<String>>() {
                @Override
                public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                    LogUtils.d("uploaad onSubscribe...."+d);
                }

                @Override
                public void onNext(@io.reactivex.annotations.NonNull BaseResponseBean<String> stringBaseResponseBean) {
//                    LogUtils.d("uploaad onNext...."+stringBaseResponseBean.getData());
                }

                @Override
                public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                    LogUtils.d("uploaad onError...."+e);
                }

                @Override
                public void onComplete() {
                    LogUtils.d("uploaad onComplete....");
                }
            });
    }
}  
